package utils

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"fmt"
	"github.com/go-xorm/xorm"
	"time"
)

type VerifyCode struct {
	Mobile string // 要发送的手机号
	Code   string // 要发送的验证码
}

func NewVerifyCode(mobile, code string) *VerifyCode {
	return &VerifyCode{
		Mobile: mobile,
		Code:   code,
	}
}

// 发送验证码
func (v *VerifyCode) Send() error {
	mobile := NewMobile(v.Mobile, "814605", []string{v.Code})
	return mobile.SendSms()
}

// 检查手机验证码是否正确
func (v *VerifyCode) Check() (bool, string) {
	var err error
	var ok bool
	var db *xorm.Engine

	db, err = datasourse.NewMasterOrm()
	if err != nil {
		return false, fmt.Sprintf("无法连接数据库：%s", err.Error())
	}

	verifyCode := new(models.Verify)
	ok, _ = db.Table("verify").
		Where("`key` = ?", v.Mobile).Get(verifyCode)
	if !ok {
		return false, "请先获取验证码"
	}
	if verifyCode.Code != v.Code {
		return false, "验证码不正确"
	}

	nowTime := time.Now().Unix()
	allowTime := verifyCode.SendTime.Add(5 * time.Minute).Unix()
	if nowTime > allowTime {
		return false, "验证码已失效，请重新获取"
	}

	return true, ""
}
